package com.mspbots.core.wise.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mspbots.core.AbstractBaseController;
import com.mspbots.core.wise.model.TenantRule;
import com.mspbots.core.wise.service.TenantRuleService;
import com.mspbots.cw.request.EscalationDTO;
import com.mspbots.cw.request.TenantRuleDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.Callable;


/**
 * com.mspbots.core.controller.TenantRuleController
 * update api path remove {tenant}
 *
 * @author Jun Zhou
 * @date 12:09 2019/6/28
 **/
@RestController
@RequestMapping("tenant/rule")
public class TenantRuleController extends AbstractBaseController<TenantRule, TenantRuleService> {

    public static final String REDIS_KEY_PREFIX_TENANT = "MSPBOTS:CONFIG:TENANT:";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("list-analysis")
    public Callable listAnalysis(TenantRule query) {
        return () -> service.listAnalysis(query);
    }

    @GetMapping("detail")
    public Callable detail(TenantRuleDTO query) {
        return () -> service.detail(query);
    }

    @RequestMapping("count")
    public Callable count(TenantRule query) {
        return () -> service.count(new QueryWrapper<>(query));
    }

    @PutMapping(path = "/{id}/update")
    public Callable updateById(@RequestBody TenantRule entity) {
        return () -> {
            service.updateById(entity);
            stringRedisTemplate.opsForValue().set(REDIS_KEY_PREFIX_TENANT + entity.getTenantId() + ":" + entity.getRuleId() + "_sending", entity.getSending().toString());
            stringRedisTemplate.opsForValue().set(REDIS_KEY_PREFIX_TENANT + entity.getTenantId() + ":" + entity.getRuleId() + "_enable", entity.getEnable().toString());
            return entity;
        };
    }

    @PostMapping("save-batch")
    public Callable saveBatch(@RequestBody Map<String, Object> params) {
        Long tenantId = Long.valueOf(params.get("tenantId").toString());
        long[] ruleIds = StrUtil.splitToLong(params.get("ruleIds").toString(), ",");
        return () -> service.saveBatch(tenantId, ruleIds);
    }

    @GetMapping("page-detail")
    public Callable selectPage(Page<TenantRuleDTO> page, TenantRuleDTO queryParams) {
        return () -> service.pageDetail(page, queryParams);
    }

    @GetMapping("getEscalation")
    public Callable getEscalation(TenantRuleDTO query) {
        return () -> service.getEscalation(query);
    }

    @GetMapping("selectEscalationParams")
    public Callable selectEscalationParams(EscalationDTO query) {
        return () -> service.selectEscalationParams(query);
    }
}
